package com.supeng.PMdepot.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.supeng.PMdepot.ItemDecoration.SpaceItemDecoration;
import com.supeng.PMdepot.R;
import com.supeng.PMdepot.adapter.WfChaXiangAdapter;
import com.supeng.PMdepot.base.BaseActivity;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.ChaiXiangInfo;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.entity.WfChaXiang;
import com.supeng.PMdepot.entity.WfChaiXiangReq;
import com.supeng.PMdepot.net.Api;
import com.supeng.PMdepot.net.NetUtils;
import com.supeng.PMdepot.util.KeyboardUtils;
import com.supeng.PMdepot.util.ToastUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import zpSDK.zpSDK.zpBluetoothPrinter;

/**
 * 外发拆箱
 */
public class WFChaXiangActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.et_kucun)
    EditText etKucun;
    @BindView(R.id.vv_blue2)
    View vvBlue2;
    @BindView(R.id.tv_cptm)
    TextView tvCptm;
    @BindView(R.id.tv_cpmingcheng)
    TextView tvCpmingcheng;
    @BindView(R.id.tv_zhongliang)
    TextView tvZhongliang;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.btn_printer)
    Button btnPrinter;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.btn_printerOne)
    Button btnPrinterOne;
    private String chanpin;
    public static BluetoothAdapter myBluetoothAdapter;
    public String SelectedBDAddress;
    private TextView tv_connectBlooth;
    private ChaiXiangInfo chaiXiangInfo;
    private WfChaXiangAdapter homeAdapter;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    private  List<WfChaXiang> wfChaXiangList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //弹出键盘滚动问题
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_wfchaxiang);
        unbinder = ButterKnife.bind(this);
        initView();
        initData();
        initAdapter();
    }
    private void initAdapter() {

        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(0.5f).setSpaceColor(getResources().getColor(R.color.item_press2)));
        homeAdapter = new WfChaXiangAdapter();
//        homeAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
//                if(position==0){
//                    return false;
//                }
//                final WfChaXiang wfChaXiang = (WfChaXiang) adapter.getData().get(position);
//                AlertDialog dialog = new AlertDialog.Builder(getActivity())
//                        .setTitle("是否删除表面处理" + wfChaXiang.getColor() + "这条记录")
//                        .setNegativeButton("是", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                doDelete(position);
//                                dialog.dismiss();
//                            }
//                        })
//                        .setPositiveButton("否", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        })
//                        .show();
//                return false;
//            }
//        });
        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
        rvList.setAdapter(homeAdapter);
        homeAdapter.setNewData(null);
        homeAdapter.setEtOncliLisnter(etOncliLisnter);
    }
    WfChaXiangAdapter.EtOncliLisnter etOncliLisnter= new WfChaXiangAdapter.EtOncliLisnter() {
        @Override
        public void etWeight(TextView v,int position) {
            jsWeight(v,position);
            KeyboardUtils.hideSoftInput(v, getActivity());
            getJiaoDian(etKucun);
        }

        @Override
        public void etCount(TextView v,int position) {
            jsCount(v,position);
            KeyboardUtils.hideSoftInput(v, getActivity());
            getJiaoDian(etKucun);
        }
    };
    private void jsCount(TextView v,int position) {
        String text = v.getText().toString();
        int count=0;
        if (!TextUtils.isEmpty(text)) {
            count = Integer.parseInt(text);
        }

        WfChaXiang wfChaXiangTop=homeAdapter.getData().get(0);
        int shengyuCount=wfChaXiangTop.getCount();
        if(count>shengyuCount){
            count=shengyuCount;
        }
        WfChaXiang wfChaXiangDq= homeAdapter.getData().get(position);
        if(count==0){
            wfChaXiangTop.setCount(shengyuCount+wfChaXiangDq.getCount());
            wfChaXiangDq.setCount(count);
            homeAdapter.notifyItemChanged(position);
            homeAdapter.notifyItemChanged(0);
        }else{
            int rshengyuCount=count-wfChaXiangDq.getCount();
            wfChaXiangTop.setCount(shengyuCount-rshengyuCount);
            wfChaXiangDq.setCount(count);
            homeAdapter.notifyItemChanged(position);
            homeAdapter.notifyItemChanged(0);
        }
    }

    private void jsWeight(TextView v,int position) {
        String text = v.getText().toString();
        float textFloat=0;
        if (!TextUtils.isEmpty(text)) {
            textFloat = Float.parseFloat(text);
        }
        WfChaXiang wfChaXiangTop=homeAdapter.getData().get(0);
        float shengYuFloat=wfChaXiangTop.getWeight();
        int shengyuCount=wfChaXiangTop.getCount();
        if(textFloat>shengYuFloat){
            ToastUtils.show("拆分重量不能大于待拆分总重量,现在默认最大剩余重量");
            textFloat=shengYuFloat;
        }
        int count = jisuanshuliang(textFloat, chaiXiangInfo.getInfo().getDanzhong());
        if(count>shengyuCount){
            count=shengyuCount;
        }
        WfChaXiang wfChaXiangDq= homeAdapter.getData().get(position);
        if(textFloat==0){
            wfChaXiangTop.setWeight(jisuanzhongliangJIA(shengYuFloat, wfChaXiangDq.getWeight()));
            wfChaXiangTop.setCount(shengyuCount + wfChaXiangDq.getCount());
            wfChaXiangDq.setCount(count);
            wfChaXiangDq.setWeight(textFloat);
        }else {
            float shengyuFloat=jisuanzhongliang(textFloat, wfChaXiangDq.getWeight());
            int rshengyuCount=shengyuCount+wfChaXiangDq.getCount();
            wfChaXiangTop.setWeight(jisuanzhongliang(shengYuFloat, shengyuFloat));
            wfChaXiangTop.setCount(rshengyuCount - count);
            wfChaXiangDq.setCount(count);
            wfChaXiangDq.setWeight(textFloat);
        }
        homeAdapter.notifyItemChanged(position);
        homeAdapter.notifyItemChanged(0);

    }

    private void doDelete(int postion) {
        WfChaXiang wfChaXiangTop=homeAdapter.getData().get(0);
        WfChaXiang wfChaXiangdq=homeAdapter.getData().get(postion);
        float shengYuFloat=wfChaXiangTop.getWeight();
        int shengyuCount=wfChaXiangTop.getCount();
        wfChaXiangTop.setWeight(jisuanzhongliangJIA(shengYuFloat,wfChaXiangdq.getWeight()));
        wfChaXiangTop.setCount(shengyuCount+wfChaXiangdq.getCount());
        homeAdapter.remove(postion);
        homeAdapter.notifyItemChanged(0);
        rvList.smoothScrollToPosition(0);
    }
    private void initData() {

        etKucun.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 0 || actionId == 6) {
                    if (event == null) {
                        if (actionOk(v)) return true;
                    } else {
                        switch (event.getAction()) {
                            case KeyEvent.ACTION_UP:
                                if (actionOk(v)) return true;
                        }
                    }
                }
                return true;

            }
        });


    }

    private boolean actionOk(TextView v) {
       /* if (!TextUtils.isEmpty(chanpin)) {
            etKucun.setText("");
            ToastUtils.show("请等待上一个条码入库才可以进行下一条码扫描");
            return true;
        }*/
        String search = v.getText().toString();
        etKucun.setText("");
        if (TextUtils.isEmpty(search)) {
            ToastUtils.show("无效二维码");
            return true;
        }
        if (search.indexOf(Constant.ChanPinKey) == 0) {
            chanpin = search;
            if (!TextUtils.isEmpty(chanpin)) {
                searchByServer();
            }
            return true;
        } else {
            if(chaiXiangInfo!=null&&chaiXiangInfo.getInfo()!=null) {
                if (search.indexOf(Constant.Colorkey) == 0) {
                    String colcor=search.substring(1,search.length());
                    List<WfChaXiang> wfChaXiangList=homeAdapter.getData();
                    for(WfChaXiang wfChaXiang:wfChaXiangList){
                        if(colcor.equals(wfChaXiang.getColor())){
                            ToastUtils.show("已经存在此表面处理颜色");
                            return  true;
                        }
                    }
                    WfChaXiang wfChaXiang=new WfChaXiang();
                    wfChaXiang.setColor(colcor);
                    wfChaXiang.setWeight(0);
                    wfChaXiang.setCount(0);
                      homeAdapter.addData(1,wfChaXiang);
                     homeAdapter.notifyItemChanged(1);
                     rvList.scrollToPosition(0);
                      return true;
                }else{
                    ToastUtils.show("无效条码");
                    return true;
                }
            }else{
                ToastUtils.show("请先扫描产品条码");
                return true;
            }

        }

    }

    private void searchByServer() {
        wfChaXiangList=null;
        homeAdapter.setNewData(null);
        chaiXiangInfo=null;
        Api.xcsearchChaixiang(getActivity(), chanpin, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    chaiXiangInfo = (ChaiXiangInfo) rspData;
                    setUI();
                    chanpin = "";
                } else {

                    ToastUtils.show(rspData.getMsg());
                    chanpin = "";
                    chaiXiangInfo = null;
                    setUI();
                }

            }

            @Override
            public void failed(String msg) {

                ToastUtils.show(msg);
                chanpin = "";
                chaiXiangInfo = null;
                setUI();
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, ChaiXiangInfo.class);
    }

    private void setUI() {

        if (chaiXiangInfo != null && chaiXiangInfo.getInfo() != null) {
            tvCptm.setText(chaiXiangInfo.getInfo().getTiaoma() + "");
            tvCpmingcheng.setText(chaiXiangInfo.getInfo().getChanpinname() + " " + chaiXiangInfo.getInfo().getXinghao());
            tvZhongliang.setText(chaiXiangInfo.getInfo().getZhongliang() + "kg");
            tvCount.setText(chaiXiangInfo.getInfo().getShulian() + "");
            WfChaXiang wfChaXiang=new WfChaXiang();
            wfChaXiang.setCount(chaiXiangInfo.getInfo().getShulian());
            wfChaXiang.setWeight(chaiXiangInfo.getInfo().getZhongliang());
            wfChaXiang.setColor(chaiXiangInfo.getInfo().getColor());
            List<WfChaXiang> wfChaXiangList=new ArrayList<>();
            wfChaXiangList.add(wfChaXiang);
            homeAdapter.setNewData(wfChaXiangList);

        } else {
            tvCptm.setText("");
            tvCpmingcheng.setText("");
            tvZhongliang.setText("");
            tvCount.setText("");
        }
    }


    private void initView() {
        tvCpmingcheng.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvCpmingcheng.setHorizontallyScrolling(true);
        tv_connectBlooth = findViewById(R.id.tv_connectBlooth);
        SelectedBDAddress = ListBluetoothDevice();
        if (TextUtils.isEmpty(SelectedBDAddress)) {
            ToastUtils.show("请先在系统蓝牙界面配对打印设备");
            finish();
        }
        btnPrinter.setOnClickListener(this);
        etKucun.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                etKucun.setInputType(InputType.TYPE_CLASS_TEXT);
                return false;
            }
        });
        etKucun.setInputType(InputType.TYPE_NULL);
        btnPrinterOne.setOnClickListener(this);
    }
    public void getJiaoDian(EditText et){
        et.setFocusable(true);

        et.setFocusableInTouchMode(true);

        et.requestFocus();

        et.findFocus();
    }


    private static float jisuanzhongliang(float allzhongliang, float zhongliang) {
        BigDecimal b = new BigDecimal(allzhongliang - zhongliang);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }
    private static float jisuanzhongliangJIA(float allzhongliang, float zhongliang) {
        BigDecimal b = new BigDecimal(allzhongliang + zhongliang);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }
    private static int jisuanshuliang(float zhongliang, float danzhong) {
        if(danzhong==0){
            return 0;
        }else {
            BigDecimal b = new BigDecimal(zhongliang * 1000 / danzhong);
            int f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            return f1;
        }
    }

    private String ListBluetoothDevice() {

        if ((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()) == null) {
            Toast.makeText(this, "没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
            return "";
        }

        if (!myBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 2);
        }

        Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() <= 0) return "";
        for (BluetoothDevice device : pairedDevices) {
            if (device.getName().indexOf("XT") != -1) {
                tv_connectBlooth.setText("打印机:" + device.getName());
                return device.getAddress();

            }

        }
        return "";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_printer:
                saveAndPrinter();
                break;
            case R.id.btn_printerOne:
                if(wfChaXiangList!=null&&wfChaXiangList.size()>0){
                    for(WfChaXiang wfChaXiang:wfChaXiangList){
                        if(wfChaXiang.getWeight()!=0)
                        Print1(wfChaXiang);
                    }
                }else{
                    ToastUtils.show("请先拆箱再打印");
                }
                break;
        }
    }

    private void Print1(WfChaXiang wfChaXiang) {
        zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(this);
        if (!zpSDK.connect(SelectedBDAddress)) {
            Toast.makeText(this, "连接失败------", Toast.LENGTH_LONG).show();
            return;
        }
        zpSDK.pageSetup(560, 480);
        zpSDK.drawText(31, 14, "流程单号：" , 3, 0, 0, false, false);
        zpSDK.drawText(195, 14, chaiXiangInfo.getInfo().getLiuchengdanhao(), 3, 0, 1, false, false);
        zpSDK.drawText(440, 14, chaiXiangInfo.getInfo().getBiaoqianleibie() + "", 4, 0, 1, false, false);

        zpSDK.drawText(31, 64, "产品名称：", 3, 0, 0, false, false);
        zpSDK.drawText(191, 64, chaiXiangInfo.getInfo().getChanpinname()+"/"+wfChaXiang.getColor(), 3, 0, 1, false, false);
        zpSDK.drawText(31, 121, "产品规格:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 121, chaiXiangInfo.getInfo().getXinghao(), 3, 0, 1, false, false);
        zpSDK.drawText(31, 178, "工序名称：", 3, 0, 0, false, false);
        zpSDK.drawText(195, 178, chaiXiangInfo.getInfo().getGongxvmingcheng(), 3, 0, 1, false, false);
        zpSDK.drawText(95, 235, "重量:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 235,  wfChaXiang.getWeight() + "KG", 3, 0, 1, false, false);

        zpSDK.drawText(95, 292, "数量:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 292,  wfChaXiang.getCount()+"", 3, 0, 1, false, false);
        zpSDK.drawText(71, 358,  wfChaXiang.getTimer(), 2, 0, 0, false, false);
        zpSDK.drawText(388, 358, wfChaXiang.getBarcode(), 2, 0, 0, false, false);
        zpSDK.drawQrCode(367, 180, wfChaXiang.getBarcode(), 0, 5, 0);
        zpSDK.print(0, 1);

        zpSDK.printerStatus();
        int a = zpSDK.GetStatus();

        if (a == -1) { //"获取状态异常------";
            Toast.makeText(this, "获取状态异常-----", Toast.LENGTH_LONG).show();


        }
        if (a == 1) {//"缺纸----------";
            Toast.makeText(this, "缺纸----------", Toast.LENGTH_LONG).show();
        }
        if (a == 2) {
            //"开盖----------";
            Toast.makeText(this, "开盖----------", Toast.LENGTH_LONG).show();
        }
        if (a == 0) {

            //"打印机正常-------";
            // Toast.makeText(this,"打印机正常-------", Toast.LENGTH_LONG).show();
        }


        zpSDK.disconnect();
    }

    private void saveAndPrinter() {
        if (chaiXiangInfo == null || chaiXiangInfo.getInfo() == null) {
            ToastUtils.show("请先扫条码或者条码无数据");
            return;
        }
        final List<WfChaXiang> wfChaXiangList= homeAdapter.getData();
        if(wfChaXiangList!=null&&wfChaXiangList.size()>1) {
                boolean isChaXiangOk=true;
                String color="";
                for(int i=0;i<wfChaXiangList.size();i++){
                    if(i==0){
                        continue;
                    }
                    WfChaXiang wfChaXiangtt=wfChaXiangList.get(i);
                        if(wfChaXiangtt.getWeight()==0){
                            isChaXiangOk=false;
                        }
                    color=wfChaXiangtt.getColor();
                }
                //数据未填写完整
                if(isChaXiangOk==false){
                    ToastUtils.show(color+"拆箱未填写");
                    return;
                }else{
                    WfChaXiang wfChaXiang=wfChaXiangList.get(0);
                    //未拆分完全
                    if(wfChaXiang.getWeight()!=0){
                        new AlertDialog.Builder(getActivity())
                                .setCancelable(false)
                                .setTitle("拆箱重量未拆完是否继续拆箱？")
                                .setNegativeButton("继续拆箱", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("提交拆箱", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        WfChaiXiangReq wfChaiXiangReq = new WfChaiXiangReq();
                                        wfChaiXiangReq.setOldbarcode(chaiXiangInfo.getInfo().getTiaoma());
                                        wfChaiXiangReq.setWfChaXiangList(wfChaXiangList);
                                        saveByServer(wfChaiXiangReq);
                                    }
                                })
                                .show();
                    }else {
                        WfChaiXiangReq wfChaiXiangReq = new WfChaiXiangReq();
                        wfChaiXiangReq.setOldbarcode(chaiXiangInfo.getInfo().getTiaoma());
                        wfChaiXiangReq.setWfChaXiangList(wfChaXiangList);
                        saveByServer(wfChaiXiangReq);
                    }

            }


        }else{
            ToastUtils.show("没有数据拆箱");
        }

    }

    private void saveByServer(WfChaiXiangReq wfChaiXiangReq) {
        Api.wfchaixiang(getActivity(), wfChaiXiangReq, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    WfChaiXiangReq chaiXiangInsertInfo = (WfChaiXiangReq) rspData;
                    wfChaXiangList=chaiXiangInsertInfo.getWfChaXiangList();
                    for(WfChaXiang wfChaXiang:wfChaXiangList){
                        Print1(wfChaXiang);
                    }
                } else {
                    ToastUtils.show(rspData.getMsg());
                }
            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, WfChaiXiangReq.class);
    }
}
